package ca.cbc.msb.mq;

import javax.jms.JMSException;
import javax.naming.NamingException;

import ca.cbc.msb.util.ProgressReport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ca.cbc.medialib.entity.Media;
import ca.cbc.medialib.exception.ThePlatformObjectNotFoundException;
import ca.cbc.medialib.service.MediaService;
import ca.cbc.medialib.util.ApplicationContextUtil;
import ca.cbc.msb.entity.MSBMessage;
import ca.cbc.msb.gsa.GSAService;
import ca.cbc.msb.mobilemedia.MobileMediaService;
import ca.cbc.msb.mobilemedia.YospaceServiceImpl;
import ca.cbc.msb.persistence.FailedMediaPersistence;
import ca.cbc.msb.persistence.MediaPersistence;
import ca.cbc.msb.persistence.ProcessingStatusPersistence;

/**
 * JMS implementation of MessageHandler for deleting media release from GSA and/or yoSpace.
 * 
 * @author william wei
 * 
 *
 */
public class DeletedReleaseMessageHandler implements MessageHandler{

	private Logger log = LoggerFactory.getLogger(this.getClass());
    private GSAService gsaService;
    private MobileMediaService mobileMediaService;
    private MediaPersistence mediaPersistence;
    private FailedMediaPersistence failedMediaPersistence;
    private ProcessingStatusPersistence processingStatusPersistence;
    private MediaService mediaService;

    public DeletedReleaseMessageHandler() {
    	mediaService = new MediaService();
    	gsaService = new GSAService();
    	mobileMediaService = new YospaceServiceImpl();
    	mediaPersistence = ApplicationContextUtil.instance.getApplicationContext().getBean(MediaPersistence.class);
    	failedMediaPersistence = ApplicationContextUtil.instance.getApplicationContext().getBean(FailedMediaPersistence.class);
    	processingStatusPersistence = ApplicationContextUtil.instance.getApplicationContext().getBean(ProcessingStatusPersistence.class);  	
    }
    
    /**
	 * @param message MSBMessage, containing   release information           
	 * @param messageUtil MessageUtil, maintain jms connection and a series of message queues. send /receive message to/from message queues. 
	 *     
	 */
	@Override
	public void handle(MSBMessage message, MessageUtil messageUtil) throws NamingException,
			JMSException {
		log.debug(">>>DeletedReleaseMessage Received ({})", message);
		Media media = null;
		    
        try {
        	//0. commit received message
        	messageUtil.commit();
			
        	//1. get media from DB
			media = mediaPersistence.findById(message.getNotification().getReleaseId());
			message.setMedia(media);
	
			if(media == null) return;
			
			//2. delete from GSA
			gsaService.deleteFromGSA(message);
			
					
			//3. delete from yospace and DB and set theP avaiableInMobile to false
			if(media.getAvailableInMobile().equalsIgnoreCase("true") && media.getMobileId() != 0) {		        	
				mobileMediaService.deleteMedia(media.getMobileId());
				ProgressReport.instance.statusReport(message," Deleted from Yospace");
						
				//set theP avaiableInMobile to false
				try {
					log.info("Setting avaible in mobile in the P to false after deleting media({})...", media.getId() + "-" + media.getReleaseId());
					mediaService.deleteYospaceId(media.getReleaseId(), media.getId());
	                ProgressReport.instance.statusReport(message, " Available in Mobile set to false in thePlatform");
				} catch (ThePlatformObjectNotFoundException e) {
					log.warn("!This Media has already been deleted from thePlatform, no need to remove yospaceId...");
				}	
				log.info("DeletedReleaseMessage ({}) processing with theP successfully...", message);
			        
				//delete from yosapce
				mobileMediaService.deleteMedia(media.getMobileId());
			    log.info("DeletedReleaseMessage ({}) deleted from yospace successfully>>>", message);
			}
			    
			//4. delete from db
			mediaPersistence.delete(media);
        } catch (Exception e) {
        	failedMediaPersistence.save(media);
        	log.error("Unkonw error when processing delete media, abort further action.", e);
        } finally { //will remove processing flag
        	processingStatusPersistence.removeProcessingFlag(message);
        }			
	}
}
